package net.fabene.butone;

import android.app.ListActivity;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class SettingsActivity extends ListActivity {
	
	private EditText mUserText;
	private Button mButton;
    private static final int COLOR_REQUEST_CODE = 1;
	private static final int USERNAME_REQUEST_CODE = 2;
    private static final int DELETE_ID = Menu.FIRST + 1;
    private static final int COLOR_ID = Menu.FIRST + 2;
    private TagsDbAdapter mDbAdapter;
    private Cursor mTagsCursor;
    private int mAppWidgetId;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.widget_input);
		
		mDbAdapter = new TagsDbAdapter(this);
		mDbAdapter.open();
				
		updateList();
				
        mUserText = (EditText) findViewById(R.id.user_input);
        
        mButton = (Button) findViewById(R.id.submit);

        mButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				createTag();
			}
		});
        
        registerForContextMenu(getListView());
        
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras != null) {
        	mAppWidgetId = extras.getInt("appWidgetId");
        }
		super.onCreate(savedInstanceState);
	}
	
	private void updateList() {
        // Get all of the rows from the database and create the item list
        mTagsCursor = mDbAdapter.fetchAllTags();
        startManagingCursor(mTagsCursor);
        
        Log.d("Ben","TAGS FETCHED");

        // Create an array to specify the fields we want to display in the list (only TITLE)
        String[] from = new String[]{TagsDbAdapter.KEY_TITLE, TagsDbAdapter.KEY_COLOR};

        // and an array of the fields we want to bind those fields to (in this case just text1)
        int[] to = new int[]{R.id.list_text, R.id.list_color_icon};

        // Now create a simple cursor adapter and set it to display
        SimpleCursorAdapter notes = 
            new SimpleCursorAdapter(this, R.layout.list_item, mTagsCursor, from, to);
        notes.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
			
			public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
				if (columnIndex == 1) { //index for title
					TextView text = (TextView) view;
					text.setText(cursor.getString(1));
				}
				else if (columnIndex == 2) { //index for color
					ImageView iconView = (ImageView) view;
					iconView.setBackgroundColor(cursor.getInt(2));
				}
				return true;
			}
		});
        
        setListAdapter(notes);
    }
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);

		Cursor selectedItem = (Cursor) getListView().getItemAtPosition(position);
		int tagId = selectedItem.getInt(0); //get id from column 0
		String tagTitle = selectedItem.getString(1); //get title from column 1
		int tagColor = selectedItem.getInt(2); //get color form column 2
		
		mDbAdapter.updateTagWidgetId(tagId, mAppWidgetId);
		
		final Context context = SettingsActivity.this;

        // Push widget update to surface with newly set prefix
        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
        ButOneWidget.updateAppWidget(context, appWidgetManager, mAppWidgetId, tagTitle, tagColor);

        // Make sure we pass back the original appWidgetId
        Intent resultValue = new Intent();
        resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
        setResult(RESULT_OK, resultValue);
        finish();
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
	    super.onCreateContextMenu(menu, v, menuInfo);
	    menu.add(0, DELETE_ID, 1, R.string.menu_delete);
	    menu.add(0, COLOR_ID, 0, R.string.menu_color);
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		switch(item.getItemId()) {
	    case DELETE_ID:
	        mDbAdapter.deleteTag(info.id);
	        updateList();
	        return true;
	    case COLOR_ID:
	    	Intent colorIntent = new Intent(this, ColorActivity.class);
	    	colorIntent.putExtra("id", info.id);
	    	startActivityForResult(colorIntent, COLOR_REQUEST_CODE);
	    	return true;
	    }
	    return super.onContextItemSelected(item);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.settings_menu, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
	    switch (item.getItemId()) {
	    case R.id.set_username:
	        startActivityForResult(new Intent(this,UsernameActivity.class), USERNAME_REQUEST_CODE);
	        return true;
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch(requestCode) {
		case COLOR_REQUEST_CODE:
			if (resultCode == RESULT_OK) {
				Bundle goodies = data.getExtras();
				if (goodies != null) updateTagColor((int) goodies.getLong("id"),goodies.getInt("color"));
			}
			break;
		case USERNAME_REQUEST_CODE:
			if (resultCode == RESULT_OK) {
				Bundle goodies = data.getExtras();
				if (goodies != null) {
					updateUsername(goodies.getString("username"));
					updateAppWidgets();
				}
				else Toast.makeText(this, "NULL GOODIES", Toast.LENGTH_SHORT).show();
			}
			else {
				Toast.makeText(this, "BAD RESULT CODE", Toast.LENGTH_SHORT).show();
			}
			break;
		}
		
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void updateTagColor(int id, int color) {
		mDbAdapter.updateTagColor(id, color);
		updateList();
	}
	
	private void updateUsername(String username) {
		mDbAdapter.setUsername(username);
	}
	
    private void createTag() {
        String text = mUserText.getText().toString();
        if (!text.equals("")) {
        	mDbAdapter.createTag(text, 0xFF0000FF, -1);
        	mUserText.setText(null);
        	updateList();
        }
    }
    
    private void updateAppWidgets() {
    	Cursor tags = mDbAdapter.fetchAllTags();
    	startManagingCursor(tags);
		int[] appWidgetIds = new int[tags.getCount()];
		tags.moveToFirst();
		for (int i = 0; i < appWidgetIds.length; i++) {
			appWidgetIds[i] = tags.getInt(3);
			tags.moveToNext();
		}
    	AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
    	ButOneWidget.updateAppWidgets(this, appWidgetManager, appWidgetIds);
    }
    
    @Override
    protected void onPause() {
    	super.onPause();
    	updateAppWidgets();
    }
    
    @Override
    protected void onDestroy() {
    	mDbAdapter.close();
    	super.onDestroy();
    }
    
    @Override
    protected void onResume() {
    	super.onResume();
    }
	
	@Override
	protected void onStart() {
		super.onStart();
	}
}
